package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissiontServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper mapper;
    @Autowired
    private ApplicationContext ctx;

    public void save(Permission dept) {
        mapper.insert(dept);
    }

    public void delete(long id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void reload() {
        List<String> expressions = mapper.selectAllExpressions();
        Map<String, Object> beansWithAnnotation = ctx.getBeansWithAnnotation(Controller.class);
        Collection<Object> controllers = beansWithAnnotation.values();
        for (Object controller : controllers) {
            Method[] declaredMethods = controller.getClass().getDeclaredMethods();
            for (Method method : declaredMethods) {
                if (method.isAnnotationPresent(RequiredPermission.class)){
                    RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
                    String value = annotation.value();
                    String name = controller.getClass().getName();
                    String expression = name + ":" + method.getName();
                    if (!expressions.contains(expression)){
                        Permission permission = new Permission();
                        permission.setExpression(expression);
                        permission.setName(value);
                        mapper.insert(permission);
                    }
                }
            }
        }
    }
    public List<Permission> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int rows = mapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = mapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }
}
